package cn.bonoon.kernel.descriptors.impl;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashSet;

import cn.bonoon.kernel.descriptors.EmbeddedPropertyAccessor;
import cn.bonoon.kernel.descriptors.ManyPropertyAccessor;

public class ManyPropertyAccessorImpl extends AbstractEntityPropertyAccessor implements ManyPropertyAccessor{

	private final String relationshipFieldName;
	private Class<?> actualType;
	
	public ManyPropertyAccessorImpl(Class<?> cls, String mappedName,
			Field field, EmbeddedPropertyAccessor embeddedProperty, String relationshipFieldName){
		super(cls, mappedName, field, embeddedProperty);
		this.relationshipFieldName = relationshipFieldName;

		Type ty = field.getGenericType();
		if(ty instanceof ParameterizedType){
			ParameterizedType pt = (ParameterizedType)ty;
			Type[] ts = pt.getActualTypeArguments();
			if(ts.length > 0) actualType = (Class<?>)ts[0];
		}
	}

	@Override
	public Class<?> getActualType() {
		return actualType;
	}

	@Override
	public boolean isList() {
		return type.isAssignableFrom(ArrayList.class);
	}

	@Override
	public boolean isSet() {
		return type.isAssignableFrom(HashSet.class);
	}

	@Override
	public boolean isInterface() {
		return type.isInterface();
	}

	@Override
	public Method removeMethod() throws Exception{
		return type.getDeclaredMethod("remove", int.class);
	}
	
	@Override
	public Method emptyMethod() throws Exception {
		return type.getDeclaredMethod("isEmpty");
	}

	public String getRelationshipFieldName() {
		return relationshipFieldName;
	}
}
